package com.pengpeng.jwt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.pengpeng.jwt.constant.JWTConstant;
import com.pengpeng.jwt.entity.User;
import com.pengpeng.jwt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Describe:
 * Created by AlexP on 2021/11/18.
 */
@RestController
@Slf4j
public class UserController {

    private final String USERNAME = "admin";
    private final String PASSWORD = "123456";
    @GetMapping("/login")
    public Map<String,Object> login(@RequestBody User user){
        log.info("用户名：{}", user.getUsername());
        log.info("password: {}", user.getPassword());

        Map<String,Object> map = new HashMap<>();

        if (USERNAME.equals(user.getUsername()) && PASSWORD.equals(user.getPassword())){
            Map<String,String> payload = new HashMap<>();
            payload.put("id",user.getId());
            payload.put("username",user.getUsername());
            String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","登录成功");
            map.put("Authorization", JWTConstant.TOKEN_PREFIX +token);
        }else{
            map.put("state",false);
            map.put("msg","账号或密码错误");
            map.put("Authorization","");
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader(JWTConstant.TOKEN_HEADER);
        DecodedJWT verify = JWTUtils.verify(token.replace(JWTConstant.TOKEN_PREFIX,""));
        String id = verify.getClaim("id").asString();
        String username = verify.getClaim("username").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", username);

        //TODO 业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "请求成功");
        return map;
    }
}
